package study.springboot.mvc.service.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

@Slf4j
@Service("easyExcelService")
public class EasyExcelService {

    private static final int BATCH_MAX_COUNT = 5;

    /**
     * 导入
     */
    public void importData(MultipartFile file) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, ExcelImportData.class, new DataListener())
                    .sheet()
                    .doRead();
        } catch (Exception ex) {
            throw new RuntimeException("", ex);
        }
    }

    class DataListener extends AnalysisEventListener<ExcelImportData> {

        private List<ExcelImportData> dataLt = Lists.newArrayList();

        @Override
        public void invoke(ExcelImportData data, AnalysisContext context) {
            log.info(">>>>>> {}", data);
            //
            dataLt.add(data);
            //
            if (dataLt.size() >= BATCH_MAX_COUNT) {
                dataLt.clear();
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            log.info(">>>>>> finish");
            //
            dataLt.clear();
        }
    }

    /**
     * 导入
     */
    public List<ExcelExportData> exportData() {
        List<ExcelExportData> dataLt = Lists.newArrayList();

        dataLt.add(ExcelExportData.builder()
                .name("abc")
                .build());
        dataLt.add(ExcelExportData.builder()
                .name("123")
                .build());

        return dataLt;
    }
}
